package dbutil;

import java.sql.*;

public class DBUtil {
		public static Connection conn=null;
		public static Statement stat=null;
		public static PreparedStatement ps=null;
		public static ResultSet rs=null;
		public Connection getConn(){
			try {
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("连接数据库...");
			conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/n-m-s?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8","root","123456");
			System.out.println("连接成功");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return conn;
		}
		public ResultSet getResult(String sql,String []args){
			rs=null;
			if(conn==null){
				conn=this.getConn();
			}
			try {
				ps=conn.prepareStatement(sql);
				for (int i=0;i<args.length;i++) {
					ps.setString(i+1,args[i]);
			}
			rs=ps.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return rs;
		}
		
		
		public ResultSet getResult(String sql){
			rs=null;
			if(conn==null){
				conn=this.getConn();
			}
			try {
				stat=conn.createStatement();
				rs=stat.executeQuery(sql);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return rs;
		}
		
		
		public int executeSql(String sql,String []args){
			int result=0;
		if(conn==null){
			conn=this.getConn();
		}
		try {
			ps=conn.prepareStatement(sql);
			for (int i=0;i<args.length;i++) {
				ps.setString(i+1,args[i]);
			}
			rs=ps.executeQuery();
			result =stat.executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return result;
		}
		
		
		public int executeSql(String sql){
			int result=0;
		if(conn==null){
			conn=this.getConn();
		}
		try {
			stat=conn.createStatement();
			result =stat.executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return result;
		}
		
		
		public void release(){
			try {
				if(rs!=null)
					rs.close();
				if(stat!=null)
					stat.close();
				if(conn!=null)
					conn.close();
				System.out.println("关闭数据库");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
		
		
}
